import React, { useState, Fragment } from 'react';
import { Form, message, ConfigProvider, Radio } from 'antd';
import cn from 'classnames';
import { FormContainer } from '@/components/UserForm';
import styles from '../index.less';
import { jsonFormWork, jsonFormFamily } from '../jsonForm';

let initFamilyKey = 0;
let initWorkKey = 0;
const formItemLayout = {
    labelCol: {
        md: { span: 4 },
        xs: { span: 24 },
        sm: { span: 24 }
    },
    wrapperCol: {
        md: { span: 7 },
        xs: { span: 24 },
        sm: { span: 24 }
    }
};
const Form2 = ({ form, getComponent, entryUser, returnValue, getArrKeys }) => {
    const { getFieldDecorator } = form;

    const [familyKeys, setFamilyKeys] = useState([initFamilyKey]);
    const [workKeys, setWorkKeys] = useState([initWorkKey]);

    const [removeFamilyIds, setRemoveFamilyIds] = useState([]);
    const [removeWorkIds, setRemoveWorkIds] = useState([]);

    getFieldDecorator('familyKeys', { initialValue: [0] }); // 用于保存keys的字段，方便外面可以取之到keys
    getFieldDecorator('workKeys', { initialValue: [0] });

    getFieldDecorator('removeFamilyIds', { initialValue: [] }); // 维护dto里被删的id项
    getFieldDecorator('removeWorkIds', { initialValue: [] });

    const computedValidLength = (removedIdsStr, keys) => {
        const removeId = form.getFieldValue(removedIdsStr);
        return keys.length - removeId.length;
    };

    const showErrorMessage = () => {
        message.error('至多添加10个');
    };

    // eslint-disable-next-line consistent-return
    const addFormList = type => {
        if (type === 'family') {
            if (computedValidLength('removeFamilyIds', familyKeys) >= 10) {
                return showErrorMessage();
            }
            initFamilyKey += 1;
            familyKeys.push(initFamilyKey);
            setFamilyKeys([...familyKeys]);
            form.setFieldsValue({
                familyKeys
            });
        } else if (type === 'work' && workKeys.length < 10) {
            if (computedValidLength('removeWorkIds', workKeys) >= 10) {
                return showErrorMessage();
            }
            initWorkKey += 1;
            workKeys.push(initWorkKey);
            setWorkKeys([...workKeys]);
            form.setFieldsValue({
                workKeys
            });
        } else {
            message.error('至多添加10个');
        }
    };
    // 删除组件
    const deleteGroup = (type, targetKey, deleteId) => {
        let newKeys = [];
        if (type === 'family') {
            if (deleteId) {
                // 删除的时候存储了这个id
                const removeId = [...removeFamilyIds, deleteId];
                setRemoveFamilyIds(removeId);
                form.setFieldsValue({
                    removeFamilyIds: removeId
                });
                return;
            }
            newKeys = familyKeys.filter(key => key !== targetKey);
            setFamilyKeys([...newKeys]);
            form.setFieldsValue({
                familyKeys: newKeys
            });
        } else if (type === 'work') {
            if (deleteId) {
                const removeId = [...removeWorkIds, deleteId];
                setRemoveWorkIds(removeId);
                form.setFieldsValue({
                    removeWorkIds: removeId
                });
                return;
            }
            newKeys = workKeys.filter(key => key !== targetKey);
            setWorkKeys([...newKeys]);
            form.setFieldsValue({
                workKeys: newKeys
            });
        }
    };

    // 渲染表单组件
    const renderFormItem = type => {
        let arr = [];
        let keys = [];
        let value = [];
        let removeIds = [];
        if (type === 'family') {
            arr = jsonFormFamily;
            keys = familyKeys;
            value = entryUser.familyDTOList || [];
            removeIds = removeFamilyIds;
        } else if (type === 'work') {
            arr = jsonFormWork;
            keys = workKeys;
            value = entryUser.workDTOList || [];
            removeIds = removeWorkIds;
        }
        return keys
            .filter(key => !removeIds.includes(value[key] && value[key].id))
            .map(key => (
                <div className={styles.block} key={type + key}>
                    {key !== 0 ? (
                        <i
                            className={cn(styles.del, 'iconfont icongms_list_icon_fail_default')}
                            onClick={() => {
                                deleteGroup(type, key, value[key] && value[key].id);
                            }}
                        />
                    ) : (
                        ''
                    )}
                    <FormContainer>
                        {arr.map(list => (
                            <Form.Item label={list.label} key={list.fileName}>
                                {getFieldDecorator(`${list.fileName}_${key}`, {
                                    rules: list.rules,
                                    initialValue: value[key] && returnValue(list.fileName, value[key])
                                })(
                                    getComponent(
                                        list.type,
                                        list.code,
                                        `${list.fileName}_${key}`,
                                        list.placeholder,
                                        value[key] && value[key].areaCode
                                    )
                                )}
                            </Form.Item>
                        ))}
                    </FormContainer>
                </div>
            ));
    };

    React.useEffect(() => {
        if (entryUser.familyDTOList && entryUser.familyDTOList.length) {
            initFamilyKey = entryUser.familyDTOList.length > 0 ? entryUser.familyDTOList.length - 1 : 0;
            setFamilyKeys(getArrKeys(entryUser.familyDTOList));
            form.setFieldsValue({
                familyKeys: getArrKeys(entryUser.familyDTOList)
            });
        }
        if (entryUser.workDTOList && entryUser.workDTOList.length) {
            initWorkKey = entryUser.workDTOList.length > 0 ? entryUser.workDTOList.length - 1 : 0;
            setWorkKeys(getArrKeys(entryUser.workDTOList));
            form.setFieldsValue({
                workKeys: getArrKeys(entryUser.workDTOList)
            });
        }
    }, [entryUser]);
    return (
        <ConfigProvider getPopupContainer={trigger => trigger.parentNode}>
            <div className="family">
                <div className={styles.title} id="form2-1">
                    家庭成员
                </div>
                {renderFormItem('family')}
                <div
                    className={styles.add}
                    onClick={() => {
                        addFormList('family');
                    }}
                >
                    +添加家庭成员信息
                </div>
            </div>
            <div className="work">
                <div className={styles.title} id="form2-2">
                    工作经历
                </div>
                <Form.Item label="工作经验" {...formItemLayout}>
                    {getFieldDecorator('workExperience', {
                        rules: [
                            {
                                required: true,
                                message: '请输入请选择工作经验'
                            }
                        ],
                        initialValue: entryUser.workExperience
                    })(
                        <Radio.Group>
                            <Radio value={1}>有</Radio>
                            <Radio value={0}>无(应届生)</Radio>
                        </Radio.Group>
                    )}
                </Form.Item>
                {form.getFieldValue('workExperience') ? (
                    <Fragment>
                        {renderFormItem('work')}
                        <div
                            className={styles.add}
                            onClick={() => {
                                addFormList('work');
                            }}
                        >
                            +添加工作经历
                        </div>
                    </Fragment>
                ) : (
                    ''
                )}
            </div>
        </ConfigProvider>
    );
};
export default Form2;
